<!-- components/UserAvatar.vue -->
<template>
  <div class="user-avatar">
    <!-- 根据 uploadable 判断是否可点击 -->
    <el-avatar
      :size="size"
      :shape="shape"
      :src="avatarUrl"
      :style="{ cursor: uploadable ? 'pointer' : 'default' }"
      @click.native="uploadable ? handleClickUpload() : null"
    ></el-avatar>

    <!-- 隐藏的文件上传 input -->
    <input
      type="file"
      ref="fileInput"
      accept="image/*"
      @change="handleFileChange"
      hidden
    />
  </div>
</template>

<script>
export default {
  name: 'UserAvatar',
  props: {
    src: {
      type: String,
      default: ''
    },
    size: {
      type: [String, Number],
      default: 'medium'
    },
    shape: {
      type: String,
      default: 'circle'
    },
    // 新增 prop：是否允许上传
    uploadable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultAvatar:
        'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      localAvatar: null
    };
  },
  computed: {
    avatarUrl() {
      if (this.localAvatar) {
        return this.localAvatar;
      }
      return this.src || this.defaultAvatar;
    }
  },
  methods: {
    handleClickUpload() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      if (!file.type.startsWith('image/')) {
        this.$message.error('请选择图片文件');
        return;
      }

      const reader = new FileReader();
      reader.onload = e => {
        this.localAvatar = e.target.result;
        this.$emit('update:src', this.localAvatar);
      };
      reader.readAsDataURL(file);
    }
  }
};
</script>